<?php

//This function returns the user name for the logged in user
function printId($client){
	
	$service = new Google_Service_Calendar($client);
	$calendar = $service->calendars->get('primary');
	return $calendar->getId();	

}

//This takes in the username entrybox and converts the
//string of usernames into an array.  This is so 
//we can check more than one username

function userNameArray($username)
{
	//$username = $username.' ';


  //parse the string for commas or semicolons.  
  $userNameArray = preg_split("/[\s,]+/", $username);
  // echo ' TEST ! <br>';
	 // foreach($userNameArray as $value)
		// echo $value.'<br>';
  
	// echo '<br><br>';
  //notes - using the dereferencing object is very important here.
   foreach($userNameArray as &$value){

	  if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $value)) {
		$value = "Invalid";		
		}
	} 
  //verify that each array member is a valid email address.
  //If not, we will replace it with an error
  //echo 'The print_r of the arrays <br>';
	
  return $userNameArray;
  
}

//These are the functions that deal with time
function todaysDate()
{
	$objDateTime = new DateTime('NOW');
	$isoDate = $objDateTime->format(DateTime::ISO8601);
	return $isoDate;
}

/*******************************************************************
CONVERT DATE FROM PRETTY PRINT TO DATE_TIME FORMAT
*  		This function converts the date from datepicker
		and converts it into the Google API datetime format.
		2014/06/10 10:47 to 2014-06-27T10:00:00-05:00
		written by Daniel Pflieger 6/10/2014 
********************************************************************/
function convertDate($date){
	$returnDate = '';

	//Split the string into an array
	str_split($date);

	//read in first four numbers of date, append to $returndate
	for($i = 0 ; $i < 4 ; $i++)
		$returnDate = $returnDate.$date[$i];
	//append the '-'
		$returnDate = $returnDate.'-'.$date[5].$date[6].'-'.$date[8].$date[9];
		$returnDate = $returnDate.'T';
	for($i = 11; $i<16; $i++)
		$returnDate = $returnDate.$date[$i];
	$returnDate = $returnDate.':00-05:00';
		


	return $returnDate;
}

/*******************************************************************
CONVERT DATE DATE_TIME FORMAT to PRETTYPRINT
*  		This function converts the date from datepicker
		and converts it into the Google API datetime format.
		2014/06/10 10:47 to 2014-06-27T10:00:00-05:00
		written by Daniel Pflieger 6/10/2014 
********************************************************************/
function convertDate2PP($date){
	$returnDate = '';
	$year = '';
	$month = '';
	$day = '';
	$time = '';
	
	//Split the string into an array
	str_split($date);

	//read in first four numbers of date, append to $returndate
	for($i = 0 ; $i < 4 ; $i++)
		$year = $year.$date[$i];
	//append the '-'
		$month = $month.$date[5].$date[6];
		$day = $day	.$date[8].$date[9];
			
	for($i = 11; $i<16; $i++)
		$time = $time.$date[$i];
	$returnDate = $month.'/'.$day.'/'.$year.' @ '.$time;
		


	return $returnDate;
}
































/*findFreeBusyByEmail:
	inputs:
		$id : emailaddress@onid.oregonstate.edu
		$client: this is a created by the main program.
		$minTime: minTime as defined by the Google API
		$finish: maxTime as defined by the Google API
		
	outputs:
		This function returns a FreeBusyResponse Object.  For php there 
		isn't a lot of information about this.  It took me a long time to 
		figure out how to handle this object, but the most important advice
		is to learn how to handle multi-level arrays in php.

		To get the busy/free times from the returned object, call
		printFreeBusy($freeBusyResponse)*/
function findFreeBusyByEmail($id, $client, $minTime, $maxTime){


	if ($client->getAccessToken() && !empty($id) ) {

		
		// First we create two objects, one for the service and one for the request
		// The request is holds the options that we are sending to the server.
		$freeBusyService = new Google_Service_Calendar($client);
		$request = new Google_Service_Calendar_FreeBusyRequest();

		// creating an item array, since we can be sending more than one object

		// Create the items array
		$items = array(); //store the id's

		$item = new Google_Service_Calendar_FreeBusyRequestItem();
		$item->setId($id);
		$items[]=$item;


		$request->setTimeMin($minTime);
		$request->setTimeMax($maxTime);
		$request->setTimeZone('UTC');
		$request->setItems($items);

		//Make the request from the Google Freebusy API
		$freebusyf = $freeBusyService->freebusy->query($request);	
		
	if (!empty($freebusyf))
		return $freebusyf;
	}
 }
 //Returns free busy mins
 function getFreeBusyMin($freeBusyResponse, $index)
 {
	
	return $freeBusyResponse->calendars[$id]['busy'][$index]['start'];
 }
 
 
 //Returns free busy maxes
  function getFreeBusyMax($freeBusyResponse, $index)
 {
	return $freeBusyResponse->calendars[$id]['busy'][$index]['end'];
 }
 
 //This  function takes in an id, the freebusy response, 
 //a start time and a finish time.  There is some output
 //to the user.  This is a simple (probably not the best)
 //code to display to the user. 
 function displayAllBusy($id, $response, $start, $finish){
	echo '<br><Br> Returned Busy Times for ';
	echo $id;
	echo '<br>';
		
 	$count = sizeof($response->calendars[$id]["busy"]);
	for ($i = 0; $i < $count; $i++){
		$busy = $response->calendars[$id]["busy"][$i];
		echo '<br>';
		print_r(convertDate2PP($busy['start'])); 
		echo '&nbsp&nbsp&nbsp thru &nbsp&nbsp&nbsp';
		print_r(convertDate2PP($busy['end']));
   }
  }
 
 
 //This is a simple code that prints our teams emails.  Nothing too special
 function display_group_emails(){
 echo'
	<br><br>
	pflieged@onid.oregonstate.edu<br>
	putnamj@onid.oregonstate.edu<br>
	reysda@onid.oregonstate.edu<br>
	';
 
 }
 

 //This is a function that displays the different outputs when returning a freebusy
 //response.  This function is only added in the code for the programmer who wants to learn
 //more about the freebusy respose object.
 function explainOutput($response)
 {
	echo '<b> This explains what outlook should look like </b><br>';
	echo 'print_r $response <br>';
	print_r($response);
	
	echo '<br><br>echo $response does nothing<br>';
	//echo $response;
	
	echo '<br><br> var_dump <br>';
	var_dump($response);
	
	echo '<br><br> print_r($response->calendars) <br>';
	print_r($response->calendars);
	
	echo '<br><br> var_dump($response->calendars)<br>';
	var_dump($response->calendars);
	
	
	echo '<br><br> print_r($response->calendars["pflieged@onid.oregonstate.edu"]) <br>';
	print_r($response->calendars['pflieged@onid.oregonstate.edu']);
	
	echo '<br><br> var_dump($response->calendars["pflieged@onid.oregonstate.edu"]) <br>';
	var_dump($response->calendars['pflieged@onid.oregonstate.edu']);
	
	
	echo '<br><br> print_r($response->calendars["pflieged@onid.oregonstate.edu"]["busy"]) <br>';
	print_r($response->calendars['pflieged@onid.oregonstate.edu']['busy']);
	
	echo '<br><br> var_dump($response->calendars["pflieged@onid.oregonstate.edu"]["busy"]) <br>';
	var_dump($response->calendars['pflieged@onid.oregonstate.edu']["busy"]);
	
	echo '<br><br> print_r($response->calendars["pflieged@onid.oregonstate.edu"]["busy"][0]) <br>';
	print_r($response->calendars['pflieged@onid.oregonstate.edu']['busy'][0]);
	
	echo '<br><br> var_dump($response->calendars["pflieged@onid.oregonstate.edu"]["busy"][0]) <br>';
	var_dump($response->calendars['pflieged@onid.oregonstate.edu']["busy"][0]);
	
	echo '<br><br> print_r($response->calendars["pflieged@onid.oregonstate.edu"]["busy"][0]["end"]) <br>';
	print_r($response->calendars['pflieged@onid.oregonstate.edu']['busy'][0]['end']);
	
	echo '<br><br> var_dump($response->calendars["pflieged@onid.oregonstate.edu"]["busy"][0]["end"]) <br>';
	var_dump($response->calendars['pflieged@onid.oregonstate.edu']["busy"][0]['end']);
	
	echo '<br><br> This is where the parsing gets interestine <br><br>';
	
	echo '<br><br> print_r($response->calendars["pflieged@onid.oregonstate.edu"]["busy"][0]["end"][0]) <br>';
	print_r($response->calendars['pflieged@onid.oregonstate.edu']['busy'][0]['end'][0]);
	
	echo '<br><br> var_dump($response->calendars["pflieged@onid.oregonstate.edu"]["busy"][0]["end"][0]) <br>';
	var_dump($response->calendars['pflieged@onid.oregonstate.edu']["busy"][0]['end'][0]);
	
	echo '<br><br> using a for loop to parse the string <br><br>';
	
	
	$count = sizeof($response->calendars['pflieged@onid.oregonstate.edu']["busy"]);
	for ($i = 0; $i <= $count; $i++){
		$busy = $response->calendars['pflieged@onid.oregonstate.edu']["busy"][$i];
		echo '<br>';
		print_r($busy['start']); echo ' ';
		print_r($busy['end']);
		
	}
	
	}
	
	
	//This was taken from stackoverflow for pretty printing json objects
	function prettyPrint($json )
{
    $result = '';  	
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 



?>